// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../../api/Api.dart';
import '../../entity/User.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import '../dialog/LoadingDialog.dart';
import '../dialog/SuccessDialog.dart';
import '../dialog/FailDialog.dart';

import 'package:medical_pro_flutter/utils/StringUtils.dart';

class ChangeInfoPage extends StatefulWidget {
  ChangeInfoPage({Key? key}) : super(key: key);

  @override
  _ChangeInfoPageState createState() => _ChangeInfoPageState();
}

class _ChangeInfoPageState extends State<ChangeInfoPage> {
  TextEditingController jobnumController =
      TextEditingController(text: User.job_num);
  TextEditingController nameController = TextEditingController(text: User.name);
  TextEditingController hospitalController =
      TextEditingController(text: User.hospital);
  TextEditingController phonenumController =
      TextEditingController(text: User.phone_num);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('修改信息'),
        ),
        body: SingleChildScrollView(
          child: Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.all(5),
            child: Column(
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    onTap: () => Fluttertoast.showToast(
                      msg: '工号不可修改',
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      timeInSecForIosWeb: 3,
                      backgroundColor: Colors.red,
                      textColor: Colors.white,
                      fontSize: 16.0,
                    ),
                    enabled: false,
                    controller: jobnumController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '工号'),
                  ),
                ),
                Container(
                    margin: const EdgeInsets.all(10),
                    child: TextField(
                      controller: nameController,
                      decoration: InputDecoration(
                          border: OutlineInputBorder(), labelText: '姓名'),
                    )),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    controller: hospitalController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '医院'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    controller: phonenumController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '联系电话'),
                  ),
                ),
                Container(
                    margin: const EdgeInsets.all(30),
                    child: ElevatedButton(
                      child: Text('确认修改'),
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(Colors.blue),
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.0))),
                      ),
                      onPressed: _submit,
                      // color: Colors.blue,
                      // highlightColor: Colors.blue[700],
                      // colorBrightness: Brightness.dark,
                      // splashColor: Colors.grey,
                      // child: Text('Submit'),
                      // shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
                      // onPressed: () {},
                    )),
              ],
            ),
          ),
        ));
  }

  Future<void> _submit() async {
    var job_num = jobnumController.text;
    var name = nameController.text;
    var hospital = hospitalController.text;
    var phone_num = phonenumController.text;
    var password = User.password;
    var type = User.type;

    if (name == User.name &&
        hospital == User.hospital &&
        phone_num == User.phone_num) {
      Fluttertoast.showToast(
        msg: '您未修改任何信息',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      return;
    }
    if (!StringUtils.isPhone(phonenumController.text.trim())) {
      Fluttertoast.showToast(
        msg: '手机号输入有误',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }

    String url = API.BASE_URL + API.CHANGE_INFO;
    print('请求的url：$url');

    Response response;

    try {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return LoadingDialog(text: '加载中...');
          });

      var dio = Dio();
      var formData = FormData.fromMap({
        'job_num': job_num,
        'name': name,
        'hospital': hospital,
        'password': password,
        'phone_num': phone_num,
        'type': type,
      });
      response = await dio.put(url, data: formData);
      print('code:${response.statusCode}');

      //拿到返回数据，先实例化更改User，再同步到本地数据库
      if (response.statusCode == 200) {
        // Map<String, dynamic> changedInfo = json.decode(response.data);
        Map<String, dynamic> changedInfo =
            Map<String, dynamic>.from(response.data);

        User.name = changedInfo['name'];
        User.phone_num = changedInfo['phone_num'];
        User.hospital = changedInfo['hospital'];
        User.updateToLocalDB();

        Navigator.pop(context);

        showDialog(
            context: context,
            builder: (BuildContext context) {
              return SuccessDialog(text: '修改成功');
            });
      }
    } catch (e) {
      print(e.toString());
      Navigator.pop(context);

      showDialog(
          context: context,
          builder: (BuildContext context) {
            return FailDialog(text: '修改失败');
          });
    }
  }
}
